<template>
  <TableBody>
    <template #header>
      <TableHeader ref="tableHeaderRef" :show-filter="false" :title="'未归档目标'">
        <template #top-right>
          <!--          {{fatherInfo}}-->
<!--          <n-tag type="error"> {{stageMenuMap.get("0")}} : {{ fatherInfo.stageIds.get("0")?fatherInfo.stageIds.get("0"):0}} </n-tag>-->
<!--          <n-tag type="success"> {{stageMenuMap.get("1")}} : {{fatherInfo.stageIds.get("1")?fatherInfo.stageIds.get("1"):0}} </n-tag>-->
<!--          <n-tag type="default"> {{stageMenuMap.get("3")}} : {{fatherInfo.stageIds.get("3")?fatherInfo.stageIds.get("3"):0}} </n-tag>-->
          <AddButton @add="onAddGoal" />
        </template>
      </TableHeader>
    </template>
    <template #default>
      <n-layout
          has-sider
          style="height: 320px"
      >
        <n-layout-sider
            bordered
            show-trigger
            collapse-mode="width"
            :collapsed-width="64"
            :width="150"
            :native-scrollbar="false"
            style="max-height: 320px"
        >
          <n-menu
              v-model:value="surfaceSetting.showGoalInfoId"
              :collapsed-width="64"
              :collapsed-icon-size="22"
              :options="satgeMenuOptions"
              :on-update:value="updateState"
          />
        </n-layout-sider>
        <n-layout-content content-style="padding: 24px;">
          <n-data-table
              :loading="table.tableLoading.value"
              :data="table.dataList.value as Array<object>"
              :row-key="rowKey"
              :columns="tableColumns"
              :scroll-x="500"
              :style="{ height: `${table.tableHeight.value*2}px` }"
              :flex-height="true"
              :row-props="rowProps"
              :pagination="false"
              :bordered="false"
          />
          <n-dropdown
              placement="bottom-start"
              trigger="manual"
              :x="xRef"
              :y="yRef"
              :options="options"
              :show="showDropdownRef"
              :on-clickoutside="onClickoutside"
              @select="handleSelect"
          />
        </n-layout-content>
      </n-layout>

      <!--          @update:checked-row-keys="onRowCheck"-->

    </template>
  </TableBody>
  <ModalDialog ref="modalDialogRef" @confirm="onDataFormConfirm" contentHeight="100vh">
    <template #content>
      <DataForm ref="dataFormRef" :options="formItems" :form-config="formConfig"/>
    </template>
  </ModalDialog>
</template>

<script setup lang="ts">
import useUserStore from "@/store/modules/user";
import {UseConstsStore} from "@/store/modules/consts";
import UseSurfaceSettingStore from "@/store/modules/surfaceSetting";
import {
  DataTableColumn,
  FormProps,
  MenuOption,
  NInput,
  NProgress,
  NSlider,
  TreeOption,
  useDialog,
  useMessage
} from "naive-ui";
import {computed, h, nextTick, onMounted, ref, watch} from "vue";
import {obj2Map} from "@/utils";
import {post, Response} from "@/api/http";
import {addGoal, changeGoalState, deleteGoal, getGoalsList} from "@/api/url";
import {DataFormType, FormItem, ModalDialogType} from "@/types/components";
import {renderIcon} from "@/hooks/form";
import {Book} from "@vicons/ionicons5";
import {TableActionModel, useRenderAction, useRowKey, useTable, useTableColumn} from "@/hooks/table";
import MyTime from "@/views/task/time/MyTime.vue";
import AddButton from "@/components/common/AddButton.vue";
import ModalDialog from "@/components/common/ModalDialog.vue";
import DataForm from "@/components/common/DataForm";

const userStore = useUserStore()
const useConsts = UseConstsStore()
const useSurfaceSetting = UseSurfaceSettingStore()
const message = useMessage()
const naiveDialog = useDialog()
const table = useTable()

interface GoalData {
  id?:number
  goalName?:string
  goalDesc?:string
  state?:number
  lastStartTime?:number
  timePeriods?:Array<number>
  goalScore?:number
  goalConclusion?:string
}

const rowKey = useRowKey('id')
const surfaceSetting = useSurfaceSetting.getSurfaceSetting();
const satgeMenuOptions = computed(()=>{
  return useConsts.getStateList().map(u=>{return {...u,icon:renderIcon(Book)}})
})
const stageMenuMap = computed(()=>{
  return obj2Map(useConsts.getConsts().stateMap)
})
const tableColumns = useTableColumn(
    [
      table.selectionColumn,
      // table.indexColumn,
      {
        title: 'id',
        key: 'id',
      },
      {
        title: '目标名',
        key: 'goalName',
      },
      {
        title: '描述',
        key: 'goalDesc',
        width: 100,
        ellipsis: {
          tooltip: true,
        },
      },
      {
        title: '上次开启时间',
        key: 'lastStartTime',
        render: (rowData) => {
          return h(MyTime,{
            time:rowData.lastStartTime,
            type:"datetime"
          },{})
        }
      },
      {
        title: '目标分数',
        key: 'goalScore',
        render: (rowData) => {
          return h(NProgress,{
            percentage:(rowData.goalScore?rowData.goalScore:0)/100,
            type:"line"
          },{})
        }
      },
      {
        title: '目标结论',
        key: 'goalConclusion',
        width: 100,
        ellipsis: {
          tooltip: true,
        },
      },
    ],
    {
      align: 'center',
    } as DataTableColumn
)

const key = ref(new Date().getTime());
const stateMap = computed(()=>{
  return obj2Map(useConsts.getConsts().stateMap);
})

// 获取数据
async function doRefresh() {
  try {
    // table.tableLoading.value = true;
    const data: Response = await post({
      url: getGoalsList,
      token:userStore.getToken()
    });
    const treeData = new Map(Object.entries(data.data.data));
   if(treeData.get(surfaceSetting.showGoalInfoId)) {
     table.dataList.value = treeData.get(surfaceSetting.showGoalInfoId ) as any
   } else table.dataList.value = []
  }catch(e) {
    message.error((e as Error).message)
  }finally {
    table.tableLoading.value = false;
  }
}
onMounted(doRefresh)
watch(key,doRefresh)
watch(stateMap,doRefresh)
const updateState = (key: string, item: MenuOption)=>{
  // 重新获取数据
  surfaceSetting.showGoalInfoId = key
  // console.log(key)
  doRefresh()
}
// 下拉菜单
let chooseRow:GoalData|null = null;
const options = [
  {
    label: "启动目标",
    key: "start",
  },
  {
    label: "暂停目标",
    key: "stop",
  },
  {
    label: "结束目标",
    key: "finish",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "归档目标"),
    key: "finishGoal",
  },
  {
    label: "编辑",
    key: "edit",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "删除"),
    key: "delete",
  },
];
const showDropdownRef = ref(false);
const xRef = ref(0);
const yRef = ref(0);
const onClickoutside = () => {
  showDropdownRef.value = false;
};
function onFinishGoal(params: GoalData|null, str:string, newState:number){
  if(params){
    const func = async (id:number|undefined,beginTime:number, endTime:number|null,
                        oldState:number|undefined,newState:number) => {
      try {
        const data : Response = await post({
          url: changeGoalState,
          data: {id:id,startTime:beginTime,endTime:endTime,oldState:oldState,newState:newState},
          token:userStore.getToken()
        });
        // console.log(data)
        message.success(data.msg)
      }catch(e) {
        message.error((e as Error).message)
      }finally {
        key.value = Date.now()
      }
    }
    naiveDialog.warning({
      title: '提示',
      content: '是否要选择'+str+'该目标:'+params.goalName+'？',
      positiveText: '记录上一段的时间',
      negativeText: '取消上一段的时间',
      onNegativeClick:()=>{
        func(params.id,Date.now(),null,params.state,newState)
      },
      onPositiveClick:() => {
        func(params.id,Date.now(),Date.now(),params.state,newState)
      },
    })
  }
}
const handleSelect = (key: string, node: string) => {
  // console.log(key, node);
  showDropdownRef.value = false;
  const str = key==='start'?'开启':key==='stop'?'暂停':'结束';
  if(key == "show"){
    if(chooseRow?.id)
      useSurfaceSetting.addIdToArray(chooseRow.id,useSurfaceSetting.getSurfaceSetting().showGoalId)
    //console.log(useSurfaceSetting.getSurfaceSetting().showGoalId)
  }
  if (key == "edit") {
    onUpdateGoal(chooseRow)
  }
  if (key == "delete") {
    onDeleteGoal(chooseRow)
  }
  if (key == "start") {
    onFinishGoal(chooseRow,str,0)
  }
  if (key == "stop") {
    onFinishGoal(chooseRow,str,1)
  }
  if (key == "finish") {
    onFinishGoal(chooseRow,str,3)
  }
};

// 事件
const rowProps = (row:GoalData) => {
  return {
    onContextmenu: (e: MouseEvent) => {
      e.preventDefault()
      // message.info(JSON.stringify(row, null, 2));
      showDropdownRef.value = true;
      xRef.value = e.clientX;
      yRef.value = e.clientY;
      // console.log('rowProps',row)
      chooseRow = row
    },
  };
};

// 添加表单
const formConfig = {
  labelWidth: 100,
  size: 'medium',
  labelAlign: 'right',
} as FormProps
const formItems = [
  {
    label: 'id',
    type: 'input',
    key: 'id',
    hidden:true,
    disabled:true,
    value: ref(null),
    render: (formItem) => {
      return h(NInput, {
        hidden:true,
        disabled:true,
        value: formItem.value.value,
        onUpdateValue: (val:any) => {
          formItem.value.value = val
        },
      })
    },
  },
  {
    label: '目标名',
    type: 'input',
    key: 'goalName',
    value: ref(null),
    validator: (formItem, message) => {
      if (!formItem.value.value) {
        message.error('请输入目标名')
        return false
      }
      return true
    },
    render: (formItem) => {
      return h(NInput, {
        value: formItem.value.value,
        onUpdateValue: (val:any) => {
          formItem.value.value = val
        },
        placeholder: '请输入目标名',
      })
    },
  },
  {
    label: '描述',
    key: 'goalDesc',
    value: ref(null),
    maxLength: 500,
    inputType: 'text',
    validator: (formItem, message) => {
      if (!formItem.value.value) {
        message.error('请输入角色名称')
        return false
      }
      return true
    },
    render: (formItem) => {
      return h(NInput, {
        value: formItem.value.value,
        onUpdateValue: (val:any) => {
          formItem.value.value = val
        },
        placeholder: '请输入角色描述',
        type: 'textarea',
        rows: 5,
      })
    },
  },
  {
    label: '目标满意分数',
    type: 'input',
    key: 'goalScore',
    value: ref(0),
    validator: (formItem, message) => {
      if (!formItem.value.value) {
        message.error('请输入目标名')
        return false
      }
      return true
    },
    render: (formItem) => {
      return h(NSlider, {
        value: formItem.value.value,
        step:1,
        onUpdateValue: (val:any) => {
          formItem.value.value = val
        },
        placeholder: '请输入分数',
      })
    },
  },
  {
    label: '目标总结',
    key: 'goalConclusion',
    value: ref(null),
    maxLength: 500,
    inputType: 'text',
    validator: (formItem, message) => {
      if (!formItem.value.value) {
        message.error('请输入角色名称')
        return false
      }
      return true
    },
    render: (formItem) => {
      return h(NInput, {
        value: formItem.value.value,
        onUpdateValue: (val:any) => {
          formItem.value.value = val
        },
        placeholder: '请输入角色描述',
        type: 'textarea',
        rows: 5,
      })
    },
  },
] as FormItem[]
let toAddGoal = 0;
const modalDialogRef = ref<ModalDialogType | null>(null)
const dataFormRef = ref<DataFormType | null>(null)

async function onDataFormConfirm() {
  if (dataFormRef.value?.validator()) {
    modalDialogRef.value?.toggle()
    if(toAddGoal === 0){
      await addNewGoal({...dataFormRef.value.generatorParams(), state:1})
    }else {
      await addNewGoal({...dataFormRef.value.generatorParams(), state:chooseRow?.state})
    }

  }
}
const addNewGoal = async (params:any)=>{
  try {
    // table.tableLoading.value = true;
    const data: Response = await post({
      url: addGoal,
      data: params,
      token:userStore.getToken()
    });
    // console.log(data)
    message.success(data.msg)
  }catch(e) {
    message.error((e as Error).message)
  }finally {
    key.value = new Date().getTime();
  }
}
// 操作
function onAddGoal() {
  toAddGoal = 0;
  modalDialogRef.value?.toggle()
  nextTick(() => {
    dataFormRef.value?.reset()
  })
}
function onUpdateGoal(item: any) {
  // console.log(item)
  toAddGoal = 1;
  modalDialogRef.value?.toggle()
  nextTick(() => {
    formItems.forEach((it) => {
      const key = it.key
      const propName = item[key]
      console.log(item)
      if (propName) {
        it.value.value = propName
      }
    })
  })
}
function onDeleteGoal(params: GoalData|null) {
  toAddGoal = 2;
  naiveDialog.warning({
    title: '提示',
    content: '是否要删除？',
    positiveText: '删除',
    onPositiveClick:async () => {
      try {
        // table.tableLoading.value = true;
        const data: Response = await post({
          url: deleteGoal,
          data: params,
          token:userStore.getToken()
        });
        // console.log(data)
        message.success(data.msg)
      }catch(e) {
        message.error((e as Error).message)
      }finally {
        key.value = new Date().getTime();
      }
    },
  })
}

</script>